/*
 * Favorites.cpp
 *
 *  Created on: 2014年10月11日
 *      Author: Administrator
 */

#include "Favorites.hpp"

#include "FavoritesItem.hpp"
#include "init.hpp"

#include <bb/cascades/AbstractPane>
#include <bb/cascades/Application>
#include <bb/cascades/QmlDocument>
#include <bb/data/SqlDataAccess>
#include <bb/data/DataAccessError>
#include <bb/system/SystemDialog>
#include <bb/cascades/GroupDataModel>

#include <QtSql/QtSql>
#include <QDebug>

using namespace bb::cascades;
using namespace bb::data;
using namespace bb::system;

//const QString (new init())->dbFile() = "./data/V2YCache.db";

Favorites::Favorites(QObject *parent) :
        QObject(parent), m_dataModel(0)
{
    initDataModel();
}

void Favorites::initDataModel()
{
    m_dataModel = new GroupDataModel(this);
    m_dataModel->setSortingKeys(QStringList() << "customerID");
    m_dataModel->setGrouping(ItemGrouping::None);
}

QVariantMap Favorites::createRecord(const QString &title, const QString &url,
        const QString &content)
{
    QVariantMap result;
    result["statue"] = false;
    result["message"] = "Null";

    if (title.trimmed().isEmpty() && url.trimmed().isEmpty()) {
        alert(tr("You must provide param."));
        result["statue"] = false;
        result["message"] = tr("You must provide param.");
        emit created(false);
        return result;
    }

    SqlDataAccess *sqlda = new SqlDataAccess((new init())->dbFile());

    //是否已添加過
    const QString sqlVerify = "SELECT url FROM Favorites WHERE url = :url";
    QVariantList argsList;
    argsList << url;
    QVariant verificationResult = sqlda->execute(sqlVerify, argsList);
    if ((!verificationResult.isNull()) && verificationResult.value<QVariantList>().size() > 0) {
        result["message"] = tr("Update \"%1\"").arg(title);

        const QString updateCommand = "UPDATE Favorites "
                "    SET content = :content"
                "    WHERE url = :url";

        QVariantList updateContact;
        updateContact << content << url;

        sqlda->execute(updateCommand, updateContact);
        if (!sqlda->hasError()) {
            result["statue"] = true;
        }
        sqlda->deleteLater();

        emit created(true);
        return result;
    }

    QVariantList contact;
    contact << title << url << content;
    sqlda->execute("INSERT INTO Favorites"
            "    (title,url,content) "
            "    VALUES (:title,:url,:content)", contact);

    if (!sqlda->hasError()) {
        result["statue"] = true;
        result["message"] = "Create record succeeded.";
        emit created(true);
    } else {
        const DataAccessError error = sqlda->error();
        result["statue"] = false;
        result["message"] = tr("Create record error: %1").arg(error.errorMessage());
        emit created(false);
    }
    return result;
}

void Favorites::getAccessCount()
{
    SqlDataAccess *sqlda = new SqlDataAccess((new init())->dbFile());
    const QString sql = "SELECT COUNT(*) AS SIZE FROM Favorites";
    QVariant result = sqlda->execute(sql);
    if (!result.isNull()) {
        QVariantList list = result.value<QVariantList>();
        QVariantMap map = list.at(0).value<QVariantMap>();
        emit accessCountChanged(map["SIZE"].toString());
    }else{
        emit accessCountChanged("0");
    }
}

bool Favorites::emptyAccess(){
    SqlDataAccess *sqlda = new SqlDataAccess((new init())->dbFile());
    sqlda->execute("DELETE FROM Favorites");
    if (!sqlda->hasError()) {
        return true;
    }

    return false;
};

bool Favorites::updateContent(const QString &url, const QString &content)
{
    SqlDataAccess *sqlda = new SqlDataAccess((new init())->dbFile());

    const QString sqlCommand = "UPDATE Favorites "
            "    SET content = :content"
            "    WHERE url = :url";
    QVariantMap bindings;
    bindings["url"] = url;
    bindings["content"] = content;

    bool updated = false;
    sqlda->execute(sqlCommand, bindings);
    if (!sqlda->hasError()) {
        const QString sqlVerify = "SELECT url FROM Favorites WHERE url = :url";
        QVariantList args;
        args << url;
        QVariant result = sqlda->execute(sqlVerify, args);
        if (!result.isNull() && result.value<QVariantList>().size() > 0) {
            updated = true;
        }
    }

    return updated;
}

bool Favorites::deleteRecord(const QString &customerID)
{
    bool intConversionGood = false;
    const int customerIDnumber = customerID.toInt(&intConversionGood);
    if (!intConversionGood) {
        alert(tr("You must provide valid integer key."));
        return false;
    }

    SqlDataAccess *sqlda = new SqlDataAccess((new init())->dbFile());
    const QString sqlVerify = "SELECT title FROM Favorites WHERE customerID = :customerID";
    QVariantList argsList;
    argsList << customerIDnumber;
    QVariant verificationResult = sqlda->execute(sqlVerify, argsList);
    if (verificationResult.isNull() || verificationResult.value<QVariantList>().size() == 0) {
        return false;
    }

    QVariantMap bindings;
    bindings["customerID"] = customerIDnumber;
    sqlda->execute("DELETE FROM Favorites WHERE customerID=:customerID", bindings);

    bool deleted = false;
    if (!sqlda->hasError()) {
        verificationResult = sqlda->execute(sqlVerify, argsList);
        if (!verificationResult.isNull() && verificationResult.value<QVariantList>().size() == 0) {
            deleted = true;
        }
    }

    return deleted;
}

QVariantMap Favorites::readContentByUrl(const QString &url)
{
    qDebug() << "readContentByUrl";
    QVariantMap result;
    result["statue"] = false;
    result["message"] = "Null";

    SqlDataAccess *sqlda = new SqlDataAccess((new init())->dbFile());

    const QString sqlQuery = "SELECT url,content FROM Favorites WHERE url = :url";

    QVariantList argsList;
    argsList << url;
    QVariant dbResult = sqlda->execute(sqlQuery, argsList);

    if (!sqlda->hasError()) {
        int recordsRead = 0;
        if (!dbResult.isNull()) {
            QVariantList list = dbResult.value<QVariantList>();
            recordsRead = list.size();
            for (int i = 0; i < recordsRead; i++) {
                QVariantMap map = list.at(i).value<QVariantMap>();
                emit contentChanged(map);
                return map;
            }
        } else {
            result["statue"] = false;
            result["message"] = "No data.";
        }
    } else {
        result["statue"] = false;
        result["message"] = "Read records failed.";
    }

    emit contentChanged(result);

    return result;
}
;

QVariantMap Favorites::readRecords()
{
    QVariantMap result;
    result["statue"] = false;
    result["message"] = "Null";

    SqlDataAccess *sqlda = new SqlDataAccess((new init())->dbFile());

    const QString sqlQuery = "SELECT id,title,url,content FROM Favorites";

    QVariant dbResult = sqlda->execute(sqlQuery);
    if (!sqlda->hasError()) {
        int recordsRead = 0;
        m_dataModel->clear();
        if (!dbResult.isNull()) {
            QVariantList list = dbResult.value<QVariantList>();
            recordsRead = list.size();
            for (int i = 0; i < recordsRead; i++) {
                QVariantMap map = list.at(i).value<QVariantMap>();
                FavoritesItem *person = new FavoritesItem(map["id"].toString(),
                        map["title"].toString(), map["url"].toString(), map["content"].toString());
                Q_UNUSED(person);
                m_dataModel->insert(person);
            }
        }

        result["statue"] = true;
        result["message"] = recordsRead;

        if (recordsRead == 0) {
            result["message"] = tr("The customer table is empty.");
        }
    } else {
        result["statue"] = false;
        result["message"] = tr("Read records failed: %1").arg(sqlda->error().errorMessage());
    }

    return result;
}

GroupDataModel * Favorites::dataModel() const
{
    return m_dataModel;
}

void Favorites::alert(const QString &message)
{
    SystemDialog *dialog; // SystemDialog uses the BB10 native dialog.
    dialog = new SystemDialog(tr("OK"), 0); // New dialog with on 'Ok' button, no 'Cancel' button
    dialog->setTitle(tr("Alert")); // set a title for the message
    dialog->setBody(message); // set the message itself
    dialog->setDismissAutomatically(true); // Hides the dialog when a button is pressed.

    bool ok = connect(dialog, SIGNAL(finished(bb::system::SystemUiResult::Type)), dialog,
            SLOT(deleteLater()));
    Q_ASSERT(ok);
    dialog->show();
}
